package com.example.spring_mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.spring_mybatis.model.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * mybatis-plus元数据插件配置(更新时间,不在数据库层面做)
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            // 创建时间和更新时间
            if (Objects.isNull(baseEntity.getCreatedAt())) {
                baseEntity.setCreatedAt(LocalDateTime.now());
            }
            if (Objects.isNull(baseEntity.getUpdatedAt())) {
                baseEntity.setUpdatedAt(LocalDateTime.now());
            }
        }

    }

    /**
     * 更新时自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            baseEntity.setUpdatedAt(LocalDateTime.now());
        }
    }
}
